<template>
    <div class="content" v-loading="dataLoading">
        <div class="uploadBtn">
            <el-button type="primary" @click="showFilesWin">添加附件</el-button>
        </div>
        <div style="padding-top: 5px; display: flex; align-items: center;"  v-for="(item, index) in filesInfo" :key="index">
            <div style="width: 70%;">
                <span style="text-align: center;">{{ item.name }}</span>
            </div>
            <div>
                <el-button type="primary" text @click="downloadFile(item.url)">下载</el-button>
                <el-popconfirm title="是否要删除该附件？" confirmButtonText="确认" cancelButtonText="取消"
                    @confirm="deleteFile(item.id)">
                    <template #reference>
                        <el-button text type="primary" size="small">删除</el-button>
                    </template>
                </el-popconfirm>
            </div>
        </div>
        <div v-if="filesInfo == null" class="no-data">
            暂无数据
        </div>
    </div>

    <!-- 添加附件弹窗 -->
    <el-dialog v-model="dialogTableVisible_addFiles" title="添加附件" width="700" align-center>
        <el-form v-loading="uploadLoading" :model="form" ref="formRef" :rules="rules" label-width="80px" :inline="false">
            <el-form-item label="附件" prop="fileList">
                <el-upload
                    class="upload-demo"
                    ref="upload"
                    accept=".docx,.zip,.pdf,.jpg,.png,.xlsx,.xls,.ppt,.pptx"
                    action="#"
                    :multiple="true"
                    :limit="5"
                    :on-change="fileChange"
                    :on-remove="fileRemove"
                    :file-list="form.fileList"
                    :before-upload="beforeUpload"
                    :on-exceed="handleExceed"
                    :auto-upload="false">
                    <el-button size="small" type="primary">选取文件</el-button>
                    <div class="el-upload__tip" style="display: inline-block;margin-left: 20px">请选择PDF、PPT、Word、Excel、图片或者ZIP包文件</div>
                </el-upload>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button type="primary" @click="dialogTableVisible_addFiles = false">
                    关闭
                </el-button>
                <el-button type="primary" @click="uploadSubmit">
                    上传
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup>

import { onMounted, ref, reactive } from "vue";
import {toast,toastWarn} from "~/composables/util"
import { api_course_file_list,api_course_file_add,api_course_file_delete } from "~/api/exam/categoryApi";


//父子传参，courseId：课程ID
const props = defineProps({
    courseId: {
        type: String, 
        default: null
    },
})

//数据加载loading
const dataLoading = ref(false)

const formRef = ref(null)

//附件列表
const filesInfo = ref([])

//上传组件
const upload = ref(null)

//上传附件loading
const uploadLoading = ref(false)

//添加附件弹窗显示控制
const dialogTableVisible_addFiles = ref(false)

//添加附件表单
const form = reactive({
    fileList: []
})
onMounted(() => {
    //加载列表数据
    getData()
})

const getData = (e) => {
    if (typeof(e) == 'number') {
        searchForm.page = e
    }
    //显示加载框
    dataLoading.value = true

    const fun = api_course_file_list(props.courseId)
        fun.then(res => {
            console.log('course files data ', JSON.stringify(res))
            filesInfo.value = res
        }).finally(() => {
        //隐藏加载框
        dataLoading.value = false;
    })
}

const showFilesWin = (url) => {
    if (formRef.value) formRef.value.resetFields()
    form.fileList = []
    dialogTableVisible_addFiles.value = true
}

//执行表单校验
const rules = {
    fileList: [
        { required: true, message: '请选择文件', trigger: 'change' }
    ]
}

// 上传组件 -------------------------------------------
// 文件改变
const fileChange = (file, fileList) => {
    console.log("=======fileChange file========" + JSON.stringify(file))
    console.log("=======fileChange fileList========" + JSON.stringify(fileList))
    form.fileList = fileList;
}

// 文件移除
const fileRemove = (file, fileList) => {
    console.log("=======fileRemove fileList========" + JSON.stringify(form.fileList))
}

// 文件超出个数限制
const handleExceed = (file, fileList) => {
    // console.log("=======handleExceed========" + JSON.stringify(fileList))
    toastWarn('一次性最多上传5个文件');
}

// 上传前 文件校验
const beforeUpload = (file, fileList) => {
    // console.log("=======beforeUpload fileList========" + JSON.stringify(fileList))
    let allowSize = 0
    fileList.forEach(file => { 
        allowSize += file.size
    }) 
    const isLt2M = allowSize / 1024 / 1024 <= 50
    if (!isLt2M) {
        toastWarn('单次上传文件大小不能超过 50MB!')
        return false;
    }
    return true;
}

//提交上的文件
const uploadSubmit = (param) => {
    //表单校验
    formRef.value.validate((valid) => {
        if (!valid) return
            //文件大小校验
            beforeUpload(null,form.fileList)
            let paramIo = new FormData()// FormData 对象
            paramIo.append('courseId', props.courseId)// 工单ID
            form.fileList.forEach(file => { 
                paramIo.append('files', file.raw)// 文件对象
            }) 
            // console.log("请求参数,文件======>",fileObj)
            console.log("请求参数,课程ID======>",props.courseId)
            //显示加载框
            uploadLoading.value = true;
            const fun = api_course_file_add(paramIo)
            fun.then(res => {
                toast("上传附件成功")
                //清空file文件
                upload.value.clearFiles(); 
                //刷新数据
                getData()
                //关闭上传弹窗
                dialogTableVisible_addFiles.value = false
            }).finally(() => {
                //隐藏加载框
                uploadLoading.value = false;
            })
    })
}
// 上传组件 -------------------------------------------

// 下载
const downloadFile = (url) => {
    window.location.href = url
}

// 删除附件
const deleteFile = (id) => {
    api_course_file_delete(id).then(res => {
        toast("删除附件成功")
        //刷新数据
        getData()
    })
}
</script>

<style lang="scss" scoped>
    .content{
        min-height: 120px;
    }
    .uploadBtn{
        text-align: right;
    }
    .no-data {
        font-size: large;
        text-align: center;
    }
</style>
